﻿using Furion;
using Furion.JsonSerialization;
using FurionApi.Demo.Core.Options;
using FurionApi.Demo.Web.Core.Filter;
using FurionApi.Demo.Web.Core.Middleware;
using FurionApi.Demo.Web.Core.Util;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using System.Threading.Tasks;

namespace FurionApi.Demo.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddConfigurableOptions<RefreshTokenSettingOptions>();
            services.AddJwt<JwtHandler>(enableGlobalAuthorize: true, jwtBearerConfigure: o =>
            {
                //o.Events = new Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerEvents()
                //{
                //    OnChallenge = context => {
                //        var statusCode = 401;
                //        var payload = JSON.Serialize(new { statusCode = statusCode, succeeded = false, errors = $"需要token" });
                //        context.HandleResponse();
                //        context.Response.ContentType = "application/json";
                //        context.Response.StatusCode = StatusCodes.Status200OK;
                //        context.Response.WriteAsync(payload);
                //        return Task.CompletedTask;
                //    },
                //    OnForbidden = context =>
                //    {
                //        var statusCode = 403;
                //        var payload = JSON.Serialize(new { statusCode = statusCode, succeeded = false, errors = $"无权限" });
                //        context.Response.ContentType = "application/json";
                //        context.Response.StatusCode = StatusCodes.Status200OK;
                //        context.Response.WriteAsync(payload);
                //        return Task.CompletedTask;
                //    },
                //    OnAuthenticationFailed = context =>
                //    {
                //        //context.Response.StatusCode = 200;
                //        return Task.CompletedTask;
                //    }
                //};
            });

            services.AddCorsAccessor();

            services.AddEventBus();
            services.AddControllers().AddMvcFilter<RequestActionFilter>()
                    .AddInjectWithUnifyResult<XnRestfulResultProvider>().AddFriendlyException();

            if (App.Configuration["Cache:CacheType"] == "RedisCache")
            {
                services.AddStackExchangeRedisCache(options =>
                {
                    options.Configuration = App.Configuration["Cache:RedisConnectionString"]; // redis连接配置
                    options.InstanceName = App.Configuration["Cache:InstanceName"]; // 键名前缀
                });
            }
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseExceptionMiddleware();
            app.UseUnifyResultStatusCodes();
            app.UseHttpsRedirection();

            // Serilog请求日志中间件---必须在 UseStaticFiles 和 UseRouting 之间
            app.UseSerilogRequestLogging();
            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}